import { defineStore } from 'pinia';
import { fetchCartList } from '@/services/shop-cart';
import { addCart,subCart } from '@/services/shop-cart';
import { ref } from 'vue';

export const useCartStore = defineStore('cartStore', () => {
    //购物车列表数据
    const cartList = ref([]);
    //添加的总数据
    const totalCartNum = ref(0);
    //总金额
    const totalAomunt = ref(0);

    //获取购物车信息
    const getCartList = async (sitNum) => {
        const { code, data, msg } = await fetchCartList(sitNum);
        if (code == 1) {
            cartList.value = data || [];
        } else {
            uni.showToast({
                title: msg,
                icon: 'none'
            })
        }
        let amount = 0, num = 0;
        (cartList.value || []).forEach(item => {
            num += item.number;
            amount += item.number * (item.amount / 100);
        })
        totalCartNum.value = num;
        totalAomunt.value = amount;
    }

    //添加
    const addCartActive = async (item,sitNum, openId) => {
        const { code, msg } = await addCart({
            ...item,
            sitNum,
            openId,
            amount: item.price
        });
        if (code == 1) {
            getCartList(sitNum);
        } else {
            uni.showToast({ title: msg });
        }
    }

    //减少
    const subCartActive= async (item,sitNum, openId) => {
        debugger
        const { code, msg } = await subCart({
            ...item,
            sitNum,
            openId,
            amount: item.price
        });
        if (code == 1) {
            getCartList(sitNum);
        } else {
            uni.showToast({ title: msg });
        }
    }

    return {
        cartList,
        totalCartNum,
        totalAomunt,
        getCartList,
        addCartActive,
        subCartActive
    }
})